package cn.edu.cxcyzx.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.cxcyzx.entity.MyFile;
import cn.edu.cxcyzx.entity.Teacher;
import cn.edu.cxcyzx.supervisor.ResultDo;
import cn.edu.cxcyzx.supervisor.ServiceFit;
import cn.edu.cxcyzx.util.MsgJSON;
import cn.edu.cxcyzx.util.PropertyPlaceholder;
import cn.edu.cxcyzx.util.UploadStatus;

@Controller
@RequestMapping("/file")
@SessionAttributes("uploadStatus")
public class FileController {
	
	@Resource
	ServiceFit serviceFit;
	private String[] fileType=new String[]{".doc",".docx",".pdf"};
	/**
	 * 文件上传
	 * @param file
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@SuppressWarnings("finally")
	@RequestMapping("uploadProjectFile")
	@ResponseBody
	public MsgJSON projectFile_upload(@RequestParam(value="re",defaultValue="1")Integer re,@RequestParam(value="projectId",defaultValue="0")int projectId,@RequestParam(value="type")int type,@RequestParam(value="file") MultipartFile file,HttpServletRequest request, HttpServletResponse response,HttpSession session){
		System.out.println("--uploadProjectFile----------");
		if(re==null||re==0){
			System.out.println("re:"+re.toString());
			return MsgJSON.fail().add("errorMsg","请完善信息.");
		}
		System.out.println(re.toString());
		System.out.println("type:"+type+",projectId:"+projectId);
		System.out.println("filesURL:"+PropertyPlaceholder.getProperty("filesURL"));
		//判断文件类型
		String fileName=file.getOriginalFilename();
		String suffix=fileName.substring(fileName.lastIndexOf(".")).trim();
		System.out.println("suffix:"+suffix);
		Arrays.sort(fileType);
		if(Arrays.binarySearch(fileType, suffix)<0){
			return MsgJSON.fail().add("errorMsg","文件格式错误，请上传后缀为.doc或.docx的文件");
		}
		//判断是否可以上传
		switch (type) {
		case 4:
			boolean b=this.upload_declareReport((String) session.getAttribute("roleID"));
			if(!b){
				return MsgJSON.fail().add("errorMsg","项目申报书已经上传！");
			}
			break;
		case 5:
			boolean b1=this.upload_analyseReport(projectId);
			System.out.println("b1:"+b1);
			if(!b1){
				return MsgJSON.fail().add("errorMsg","需求分析报告已经上传！");
			}
			break;
		case 6:
			boolean b11=this.upload_projectReport(projectId);
			if(!b11){
				return MsgJSON.fail().add("errorMsg","项目报告书已经上传！");
			}
			break;
		case 7:
			//上传任务说明书
			break;
		default:
			break;
		}
		MyFile myFile=null;
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request))//判断 request 是否有文件上传,即多部分请求...
		{
			//文件信息
			fileName=file.getOriginalFilename();
			String fileId=(new SimpleDateFormat("yyyy-MM-dd+")).format(new Date())+UUID.randomUUID().toString().replace("-", "")+fileName.substring(fileName.indexOf("."));
			String fileURL=PropertyPlaceholder.getProperty("filesURL")+"/"+fileId;
			String uploadPeopleId=(String) session.getAttribute("roleID");
			int fileType=type;
			myFile=new MyFile(fileId, fileName, fileURL, uploadPeopleId, fileType);
			try {
				file.transferTo(new File(fileURL));
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			MsgJSON.fail().add("msg", "未获取上传的文件");
		}
		System.out.println("projectId:"+projectId);
	    this.serviceFit.getMyFileService().insertFile(myFile,projectId);
		return MsgJSON.success().add("fileName", myFile.getFileName()).add("fileId", myFile.getFileId());
	}
	
	/**
	 * 文件下载
	 * @param fileId
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("downloadProjectFile")
	@ResponseBody
	public MsgJSON projectFile_download(@RequestParam(value="fileId") String fileId,HttpServletRequest request, HttpServletResponse response,HttpSession session) throws UnsupportedEncodingException{
		System.out.println(fileId);
		fileId=fileId.replace(" ", "+");
		System.out.println(fileId);
		ResultDo<String> resultDo=serviceFit.getFileService().getFileURL(fileId);
		String path=null;
		if(resultDo.isSuccess()){
			path=resultDo.getResult();
		}else{
			System.out.println("fail-----");
			return MsgJSON.fail();
		}
		try {
			System.out.println("path:"+path);
			//path=path.replace("/", "\\");
			//path=URLEncoder.encode(path, "UTF-8");
			File file=new File(path);
			 //设置响应头，控制浏览器下载该文件  
	        response.setContentType("multipart/form-data");
	        response.addHeader("Content-Disposition", "attachment;filename="+file.getName());  
	        response.addHeader("Content-Length", "" + file.length());  
	        InputStream inputStream =new BufferedInputStream(new FileInputStream(file));  
	        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
	        int len = 0;  
	        while((len = inputStream.read()) != -1){  
	            out.write(len);  
	            out.flush();  
	        }  
	        out.close();  
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return MsgJSON.success();
	}
	
	@RequestMapping(value="getLoadProgress")  
    @ResponseBody  
    public MsgJSON getLoadProgress(@RequestParam(value="uploadStatus")UploadStatus uploadStatus) {   
        if(uploadStatus==null){  
            return MsgJSON.fail();  
        }
        return MsgJSON.success().add("uploadStatus", uploadStatus);  
    }
	
	/**
	 * 上传项目申报书
	 * @param leaderId
	 * @return
	 */
	public boolean upload_declareReport(String leaderId){
		int num=serviceFit.getApplyProjectService().getApplyNumBy_liederId(leaderId);
		if(num>0){
			return false;
		}else{
			return true;
		}
	}
	/**
	 * 上传需求分析报告
	 * @param projectId
	 * @return
	 */
	public boolean upload_analyseReport(int projectId){
		String result=serviceFit.getProjectService().isUpload_analyseReport(projectId);
		if(result==null||"".equals(result.trim())){
			//未上传
			return true;
		}else{
			return false;
		}
		
	}
	/**
	 * 上传项目报告
	 * @param projectId
	 * @return
	 */
	public boolean upload_projectReport(int projectId){
		String result=serviceFit.getProjectService().isUpload_projectReport(projectId);
		if(result==null||"".equals(result.trim())){
			return true;
		}else{
			return false;
		}
	}
	
}
